#include <cblas.h> // 对于BLAS
#include <lapacke.h> // 对于LAPACK
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <cmath> 
#include <vector>
#include "Sphere.hpp"
#include "Spline.hpp"

std::string directory = "src/build/";  // 目标目录

double pi = M_PI;

// 定义计算误差的最大范数
double maxnorm(const std::vector<double>& exact, const std::vector<double>& approx) {
    double max_err = 0.0;
    for (size_t i = 0; i < exact.size(); ++i) {
        max_err = std::max(max_err, std::abs(exact[i] - approx[i]));
    }
    return max_err;
}

double F(double x)
{
    return 1/(1+25*x*x);
}

double polynomial(double x, PPFormSpline p) {
    return p.SplineReturn(x);  
}

int main()
{
    int a[5]={5,10,20,40,80};
    for (int i = 0; i < 5; i++) {
        int N=a[i];
        std::vector<double> vec;
        std::vector<double> y1;
        vec.clear();
        y1.clear();
        for(int j = 0; j<=N;j++){
            vec.push_back(-1 + 2*(double)j/N);
            y1.push_back(F(-1 + 2*(double)j/N));
        }
        double fa=50/std::pow(26,2);
        double fb=-50/std::pow(26,2);
        PPFormSpline p(vec,y1,"complete",fa,fb);
        // 生成误差向量和精确值
        std::vector<double> exact_values;
        std::vector<double> approx_values;
        std::ofstream file(directory + "data_A" + std::to_string(a[i]+1) + ".csv");
        if (!file.is_open()) {
            std::cerr << "Failed to open file" << std::endl;
            return 1;
        }

        for (double x = -1; x <= 1; x += 0.01) {
            double y = polynomial(x,p);
            file << x << "," << y << std::endl;
        }

        for (int i = 0; i < N; i++) {
            double x=1/(double)N - 1 + 2*(double)i/N;
            double exact_val = F(x);
            double approx_val = polynomial(x,p);  // 假设插值函数与目标函数一致
            exact_values.push_back(exact_val);
            approx_values.push_back(approx_val);
        }

         // 计算最大范数误差
        double max_err = maxnorm(exact_values, approx_values);

        // 打印误差和收敛率
        std::cout << "N = " << N+1 << ", Max Norm of Error = " << max_err << std::endl;

        file.close();
    }
    return 0; 
}